//
//  SyncDownloadResource.m
//  clublbiza
//
//  Created by WANG TOM on 7/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SyncDownloadResource.h"
#import "ASIHTTPRequest.h"
#import "TMDataTable.h"
#import "Resource.h"
#import "ApiLogin.h"



@implementation SyncDownloadResource
@synthesize uuid,fName;

-(void) dealloc
{
    self.uuid = nil;
    self.fName = nil;
    [super dealloc];
}
+(int) dowanloadAll
{
    
    
    TMDataTable *dt = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:[ApiLogin shareInstance]];
    NSString *conditions = [NSString stringWithString:@"downloaded=0"];
  
     
    NSArray *resource_list = [dt findAll:conditions withSort:nil];
    
    
    for ( Resource *resource_row in resource_list) {
        
        
         SyncDownloadResource *downloader = [[[SyncDownloadResource alloc] init] autorelease];
        [downloader download:resource_row.uuid fileName:resource_row.path];
         
        
         
    }
     
    [dt release];
     
    return [resource_list count];
    
}
-(void) download:(NSString *)p_uuid fileName:(NSString *)p_fName
{
    self.uuid = p_uuid;
    self.fName = p_fName;
    /*
    
    NSThread* downloadThred = [[NSThread alloc] initWithTarget:self selector:@selector(downloadThreadMethod) object:nil];
    [downloadThred start];
     */
    [self downloadThreadMethod];
}

- (void) downloadThreadMethod
{
     ApiLogin *apiLogin = [ApiLogin shareInstance];
    AppMain *appMain = [AppMain shareInstance];
    
    /*
    NSURL *url = [NSURL URLWithString:[[appMain getGateWayURL:NO] stringByAppendingFormat:@"a=download_resource&uuid=%@&sid=%@",self.uuid,apiLogin.session_id]];
    */
    TMDataTable *dt = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:apiLogin];
    Resource *row_data = (Resource *)[dt find:self.uuid];
     NSURL *url = [NSURL URLWithString:[[appMain getGateWayURL:YES] stringByAppendingFormat:@"/upload/assets/%@",row_data.path]];
    
    
    NSString *desitionPath = [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",self.fName];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDownloadDestinationPath:desitionPath];
    
    [request setDelegate:self];
    [request startAsynchronous];
    
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
   // NSString *responseString = [request responseString];
    
    // Use when fetching binary data
  //  NSData *responseData = [request responseData];
    
    ApiLogin *apiLogin = [ApiLogin shareInstance];
    TMDataTable *dt = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:apiLogin];
    
    Boolean downloadSuccessfully = NO;
    Resource *row_data = (Resource *)[dt find:self.uuid];
    NSString *resourceFilePath =  [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",row_data.path];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ( [fileManager fileExistsAtPath:resourceFilePath]) {
        NSError *attError = nil;
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:resourceFilePath error:&attError];
        if( attError == nil ) {
            NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
            unsigned long long length = [fileSizeNumber longLongValue];
            if ( length == [row_data.size longValue] ) {
                downloadSuccessfully = YES;
            }
        }
    }
   
    if ( downloadSuccessfully ) {
        NSDictionary *update_row = [NSDictionary dictionaryWithObjectsAndKeys:self.uuid,@"uuid",[NSNumber numberWithInt:1],@"downloaded", nil];
        [dt saveRow:update_row];
        [dt release];
        
        apiLogin.totalDownloadVideoCount = apiLogin.totalDownloadVideoCount - 1;
        
        if(  apiLogin.totalDownloadVideoCount == 0) {
            apiLogin.isBusySyncThread = NO;
            apiLogin.completedSync = YES;
            NSDictionary  *msgData = [NSDictionary dictionaryWithObjectsAndKeys:@"同步完成",@"msg",@"DONE",@"type", nil];
            [self sendNotificationMessage:msgData];
        }

    }
       
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void) sendNotificationMessage:(NSDictionary*) msgData
{
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter postNotificationName:@"BACKGROUND_SYNC_THREAD_STATUS"
                                      object:nil
                                    userInfo:msgData];
}

@end
